package com.android.jingweiapp.fragment.interaction;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.GetMailFeedBackXMLPhase;
import com.android.jingweiapp.XMLPhase.MailcontentXMLPhase;
import com.android.jingweiapp.XMLPhase.SubmitMailXMLPhase;
import com.android.jingweiapp.adapter.MailAdapter;
import com.android.jingweiapp.bean.MailContentBean;
import com.android.jingweiapp.bean.MailListBean;
import com.android.jingweiapp.bean.MailSubmitBean;
import com.android.jingweiapp.util.Code;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.google.gson.Gson;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 主任信箱
 */
public class MailFragment extends Fragment {

    @Bind(R.id.btn1)
    TextView btn1;
    @Bind(R.id.btn2)
    TextView btn2;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.et_id)
    EditText etId;
    @Bind(R.id.et_editor_type)
    Spinner etEditorType;
    @Bind(R.id.et_origination)
    EditText etOrigination;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.et_mail)
    EditText etMail;
    @Bind(R.id.et_address)
    EditText etAddress;
    @Bind(R.id.et_title)
    EditText etTitle;
    @Bind(R.id.et_type)
    EditText etType;
    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.et_code)
    EditText etCode;
    @Bind(R.id.im_code)
    ImageView imCode;
    @Bind(R.id.btn_retry)
    TextView btnRetry;
    @Bind(R.id.ly_mail_submit)
    ScrollView lyMailSubmit;
    @Bind(R.id.et_check_phone)
    EditText etCheckPhone;
    @Bind(R.id.ly_check)
    LinearLayout lyCheck;
    @Bind(R.id.list_mail_recall)
    ListView listMailRecall;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_content)
    TextView tvContent;
    @Bind(R.id.tv_recall)
    TextView tvRecall;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.ly_mail_content)
    RelativeLayout lyMailContent;
    @Bind(R.id.btn_submit)
    TextView btnSubmit;
    @Bind(R.id.btn_clean)
    TextView btnClean;

    private ArrayList<MailListBean.DataEntity> beans;
    private MailAdapter adapter;
    private String choosePhone;
    private String chooseId;
    private String [] editorType={"个人用户","企业用户"};//来信人类别的类型【个人用户|企业用户】
    private Adapter editorAdapter;//来信人类别的类型的适配器
    private String str_ediotrType="个人用户";
    public MailFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mail, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        btn1.setSelected(true);
        lyMailSubmit.setVisibility(View.VISIBLE);
        initSubmit();
        beans = new ArrayList<>();
        adapter = new MailAdapter(beans, getActivity());
        listMailRecall.setAdapter(adapter);

        editorAdapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item,editorType);
        etEditorType.setAdapter((SpinnerAdapter) editorAdapter);

        etEditorType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                str_ediotrType=editorType[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!btn1.isSelected()) {
                    initSubmit();
                }
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initList();
            }
        });
    }


    //初始化提交界面
    private void initSubmit() {
        btn1.setSelected(true);
        btn2.setSelected(false);
        lyMailSubmit.setVisibility(View.VISIBLE);
        listMailRecall.setVisibility(View.GONE);
        lyCheck.setVisibility(View.GONE);
        lyMailContent.setVisibility(View.GONE);

        imCode.setImageBitmap(Code.getInstance().createBitmap());

        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imCode.setImageBitmap(Code.getInstance().createBitmap());
            }
        });

        btnClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clean();
            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });

    }

    //初始化列表
    private void initList() {
     //   if (!btn2.isSelected()) {
            choosePhone = "";
            btn1.setSelected(false);
            btn2.setSelected(true);
            lyMailSubmit.setVisibility(View.GONE);
            listMailRecall.setVisibility(View.VISIBLE);
            lyCheck.setVisibility(View.GONE);
            lyMailContent.setVisibility(View.GONE);

            new MailListTask().execute();

            listMailRecall.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    lyCheck.setVisibility(View.VISIBLE);
                    listMailRecall.setVisibility(View.GONE);
                    etCheckPhone.addTextChangedListener(textWatcher);
                    choosePhone = beans.get(position).getPhoneNumber();
                    chooseId = beans.get(position).getId();
                }
            });
       // }
    }

    //清理按钮
    private void clean() {
        etAddress.setText("");
        etCode.setText("");
        etContent.setText("");
       // etEditorType.setText("");
        etMail.setText("");
        etOrigination.setText("");
        etTitle.setText("");
        etPhone.setText("");
        etId.setText("");
        etType.setText("主任信箱");
        etName.setText("");
    }

    //提交意见反馈
    private void submit() {
        if (!TextUtils.isEmpty(etAddress.getText())
                && !TextUtils.isEmpty(etCode.getText())
                && !TextUtils.isEmpty(etContent.getText())
                && !TextUtils.isEmpty(str_ediotrType)
                && !TextUtils.isEmpty(etMail.getText())
                && !TextUtils.isEmpty(etOrigination.getText())
                && !TextUtils.isEmpty(etTitle.getText())
                && !TextUtils.isEmpty(etPhone.getText())
                && !TextUtils.isEmpty(etId.getText())
                && !TextUtils.isEmpty(etType.getText())
                && !TextUtils.isEmpty(etName.getText())) {

            if (etCode.getText().toString().toUpperCase().equals(
                    Code.getInstance().getCode().toUpperCase())) {
                MailSubmitBean mailSubmitBean = new MailSubmitBean(
                        etName.getText().toString(),
                        etId.getText().toString(),
                        str_ediotrType.toString(),
                        etOrigination.getText().toString(),
                        etPhone.getText().toString(),
                        etMail.getText().toString(),
                        etAddress.getText().toString(),
                        etTitle.getText().toString(),

                        etType.getText().toString(),
                        etContent.getText().toString());
                new SubmitTask().execute(mailSubmitBean);
            } else {
                etCode.setText("");
                imCode.setImageBitmap(Code.getInstance().createBitmap());
                MyToast.getInstance().show("请核对验证码");
            }
        } else {
            MyToast.getInstance().show("请补全信息");
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (etCheckPhone.getText().toString().length() == 11) {
                if (choosePhone.equals(etCheckPhone.getText().toString())) {
                    lyCheck.setVisibility(View.GONE);
                    lyMailContent.setVisibility(View.VISIBLE);
                    new MailContentTask().execute(chooseId);
                }
            }
        }
    };

    private void dealSubmit(String str) {
        if (Boolean.parseBoolean(str)) {
            MyToast.getInstance().show("提交成功");
            clean();
        } else {
            MyToast.getInstance().show("提交失败，请重试");
            imCode.setImageBitmap(Code.getInstance().createBitmap());
        }

    }


    private void dealMailList(String str) {
        Gson gson = new Gson();
        MailListBean mailListBean = gson.fromJson(str, MailListBean.class);
        beans.clear();
        beans.addAll(mailListBean.getData());
        adapter.notifyDataSetChanged();
    }


    private void dealMailContent(String str) {
        Gson gson = new Gson();
        MailContentBean mailContentBean = gson.fromJson(str, MailContentBean.class);
        tvContent.setText(mailContentBean.getData().get(0).getReplyContent());
        tvName.setText(mailContentBean.getData().get(0).getName());
        tvRecall.setText(mailContentBean.getData().get(0).getReplyOffice());
        tvTime.setText(mailContentBean.getData().get(0).getReplyTime());
        tvPhone.setText(choosePhone);
    }

    class SubmitTask extends AsyncTask<MailSubmitBean, Integer, String> {

        @Override
        protected String doInBackground(MailSubmitBean... params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    SubmitMailXMLPhase.createParam(getActivity(), params[0]),
                    new SubmitMailXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealSubmit(str);
        }
    }

    class MailListTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetMailFeedBackXMLPhase.createParam(getActivity()),
                    new GetMailFeedBackXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealMailList(str);
        }
    }

    class MailContentTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    MailcontentXMLPhase.createParam(getActivity(), chooseId),
                    new MailcontentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealMailContent(str);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
